// 类型保护的四种实现方式
// 1.类型断言                 as 
// 2.in 语法来做类型保护       判断对象中有无该属性
// 3.typeof 语法进行保护       判断基本类型
// 4.instanceof 语法进行保护   判断实例的原型类

interface Bird {
  fly: boolean,
  sing:() => {}
}

interface Dog {
  fly: boolean,
  bark:() => {}
}

// 1.类型断言
function trainAnimal(animal:Bird | Dog){
  if(animal.fly){
    (animal as Bird).sing()
  }else{
    (animal as Dog).bark()
  }
}

// 2.in 语法来做类型保护
function trainAnimalSecond(animal:Bird | Dog){
  if('sing' in  animal){
    (animal).sing()
  }else{
    (animal).bark()
  }
}

// 3.typeof 语法进行保护
function add(first: string | number,second: string | number){
  if(typeof first==='string' || typeof second === 'string'){
    return `${first}${second}`
  }
  return first + second
}


// 4.instanceof 语法进行保护
class NumberObj {
  count: number
}
function addSecond(first: object | NumberObj,second: object | NumberObj){
  if(first instanceof NumberObj && second instanceof NumberObj){
    return first.count + second.count
  }
  return 0
}